#include "TraceDlg.h"

#include "ConnectionString.h"
#include "Comtools.h"

#include <QItemSelectionModel>
#include <QFileDialog>
#include <sstream>

#import "msado15.dll" rename_namespace("ADODB") rename("EOF", "ADOEOF")  


TraceDlg::TraceDlg(QWidget * parent, Qt::WindowFlags f)
: QDialog(parent, f)
, m_lLogId(0)
{
  setupUi(this);

  connect(pushButtonClose, SIGNAL(clicked()), this, SLOT(clickedClose()));
}
TraceDlg::~TraceDlg()
{

}

void TraceDlg::setEventName(const char* pszEventName)
{
  lineEditAppAlert->setText(pszEventName);
}

void TraceDlg::clickedClose()
{
  close();
}

void TraceDlg::setLogId(long lLogId) 
{ 
  m_lLogId = lLogId; 
  fetchTrace();
}

void TraceDlg::fetchTrace()
{
  try {
    CoInitialize(NULL);
    HRESULT hr;
    
    this->tableWidgetTrace->clearContents();
    this->tableWidgetTrace->setRowCount(0);
    this->tableWidgetTrace->setSelectionMode(QAbstractItemView::NoSelection);
    this->tableWidgetTrace->setSelectionBehavior(QAbstractItemView::SelectRows);

    _bstr_t sql =  " select * from log_trace where log_id = "+ _bstr_t(m_lLogId) +" order by log_trace_id ";

    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    ADODB::_RecordsetPtr rs;  
    rs.CreateInstance (__uuidof(ADODB::Recordset));  
    rs->Open(sql, c.GetInterfacePtr(), ADODB::adOpenStatic, ADODB::adLockOptimistic, ADODB::adCmdText);  

    int row = 0;

    if (!rs->ADOEOF) hr = rs->MoveFirst();
    if (S_OK == hr) {
      this->tableWidgetTrace->setRowCount(rs->RecordCount);
      while (S_OK == hr && !rs->ADOEOF) { 

        _bstr_t logid = rs->Fields->GetItem(L"log_trace_id")->GetValue();
        _bstr_t actionname = rs->Fields->GetItem(L"action_name")->GetValue();
        _bstr_t classname = rs->Fields->GetItem(L"class_name")->GetValue();
        _bstr_t methodname = rs->Fields->GetItem(L"method_name")->GetValue();
        _bstr_t direction = rs->Fields->GetItem(L"direction")->GetValue();

        this->tableWidgetTrace->setItem(row, 0, new QTableWidgetItem((char*)classname));
        this->tableWidgetTrace->setItem(row, 1, new QTableWidgetItem((char*)methodname));
        this->tableWidgetTrace->setItem(row, 2, new QTableWidgetItem((char*)direction));

        row++;
        hr = rs->MoveNext();
      }
    }
    try { rs->Close(); } catch (...) {}
    try { c->Close(); } catch (...) {}
  } catch (_com_error& e) {
    BSTR b;
    if (e.ErrorInfo()) {
      e.ErrorInfo()->GetDescription(&b);
      char szErr[256];
      sprintf(szErr, "Error: %s\n",_com_util::ConvertBSTRToString(b));
      OutputDebugString(szErr);
    }
  } catch (...) {
  }
}